﻿// Decompiled with JetBrains decompiler
// Type: DnProcessSimulateCommands.ToolPositioning.CApTPJumpToolViewModel
// Assembly: DnProcessSimulateCommands, Version=2402.0.0.890, Culture=neutral, PublicKeyToken=null
// MVID: A885D881-AEDF-447E-852A-6F13102E089C
// Assembly location: C:\Program Files\Tecnomatix_2402\eMPower\DotNetCommands\DnProcessSimulateCommands.dll

using DnProcessSimulateCommands.ToolPositioningInternal;
using EngineeringInternalExtension;
using EngineeringInternalExtension.AssemblyComponents.Refactoring;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using System.Windows.Input;
using Tecnomatix.DnSoftwareAnalyticsServices;
using Tecnomatix.Engineering;


namespace DnProcessSimulateCommands.ToolPositioning;

public class CApTPJumpToolViewModel : INotifyPropertyChanged
{
  private ITxLocatableObject m_tool;
  private ITxLocatableObject m_fastener;
  private bool m_compatibilityCheckType;
  private bool m_compatibilityCheckSize;
  private TxTransformation m_toolOriginalLocation;
  private bool m_jumped;
  private TxColor m_toolEmphasizeColor;
  private TxColor m_fastenerEmphasizeColor;
  private TxTransformation m_dummyToolOriginalLocation;
  private TxTransformation m_dummyFastenerOriginalLocation;
  private ITxACTool m_toolAssemblyComponent;
  private ITxACFastener m_fastenerAssemblyComponent;
  private string m_dialogSession;
  private const int m_classificaitonContourPointsNumber = 80 /*0x50*/;
  private bool m_mlAvailable = true;
  private CApTPCompatibilityChecker m_compatibilityChecker = new CApTPCompatibilityChecker();
  private string m_compatibilityResult;
  private int m_sizeMatchTolerance = 3;
  private CApTPIGraphicsDrawer _graphicsDrawer = new CApTPIGraphicsDrawer();
  private bool _classifyPreviewVisibility;
  private string _toolClassifyResult;
  private string _fastenerClassifyResult;
  private TxColor _restoreColor;
  private List<ITxLocatableObject> m_previewObjects;
  private IGraphicsPreview m_previewGraphics;

  public CApTPJumpToolViewModel(IGraphicsPreview previewGraphics)
  {
    this.m_toolEmphasizeColor = new TxColor((byte) 0, byte.MaxValue, byte.MaxValue, 1.0);
    this.m_fastenerEmphasizeColor = new TxColor(TxColor.TxColorBlue);
    this.m_dialogSession = Guid.NewGuid().ToString("N");
    this.ShowClassifyResult = false;
    this.m_previewGraphics = previewGraphics;
    this.DataGenerator = new CApTPIDataGenerator(Path.Combine(Path.GetTempPath(), "stTemp"));
    this.DataGenerator.GeneratingDataExampleCallBack = new Action<ITxObject>(this.DataGenerator_GeneratingDataExample);
    this.DataGenerator.GenerationStarted = new Action<ITxObject>(this.DataGenerator_GenerationStarted);
    this.DataGenerator.GenerationFinished = new Action<ITxObject>(this.DataGenerator_GenerationFinished);
  }

  public event PropertyChangedEventHandler PropertyChanged;

  private void OnPropertyChanged(string property)
  {
    if (this.PropertyChanged == null)
      return;
    this.PropertyChanged((object) this, new PropertyChangedEventArgs(property));
  }

  public ITxLocatableObject Tool
  {
    get => this.m_tool;
    set
    {
      if (value == this.m_tool)
        return;
      bool flag = false;
      if (this.m_tool != null)
      {
        TxDisplayableObjectEx.StopEmphasizeObject(this.m_tool as ITxDisplayableObject, this.m_toolEmphasizeColor, (TxColorEmphasizePriority) 2);
        this.m_tool.AbsoluteLocationChanged -= new TxLocatableObject_AbsoluteLocationChangedEventHandler(this.CApTPJumpToolViewModel_AbsoluteLocationChanged);
        flag = true;
      }
      this.m_tool = value;
      if (this.m_tool != null)
      {
        this.m_toolOriginalLocation = this.m_tool.AbsoluteLocation;
        TxDisplayableObjectEx.EmphasizeObject(this.m_tool as ITxDisplayableObject, this.m_toolEmphasizeColor, (TxColorEmphasizePriority) 2);
        this.m_tool.AbsoluteLocationChanged += new TxLocatableObject_AbsoluteLocationChangedEventHandler(this.CApTPJumpToolViewModel_AbsoluteLocationChanged);
        flag = true;
      }
      else
        this.m_toolOriginalLocation = (TxTransformation) null;
      this.ToolClassifyResultPreview = this.ToolClassifyResult = string.Empty;
      this.OnPropertyChanged(nameof (Tool));
      this.Jumped = false;
      this.CompatibilityResult = string.Empty;
      List<string> objSnapshotsFilePath = new List<string>();
      try
      {
        TxApplication.ActiveUndoManager.StartTransaction();
        this.RemoveFromPreview((ITxObject) this.DummyTool);
        this.DeleteObject((ITxObject) this.DummyTool);
        this.DummyTool = (ITxLocatableObject) null;
        this.ToolAssemblyComponent = (ITxACTool) null;
        if (this.m_tool != null)
        {
          this.DummyTool = this.CreateDummyObject(this.m_tool);
          if (this.DummyTool != null)
          {
            this.CreatePreview(this.DummyTool, objSnapshotsFilePath);
            this.m_dummyToolOriginalLocation = this.DummyTool.AbsoluteLocation;
            this.PreviewToolState = this.m_previewGraphics.KeepState();
          }
        }
      }
      finally
      {
        TxUndoTransactionManagerEx.CancelTransaction();
      }
      this.OnPropertyChanged("ApplyEnabled");
      this.OnPropertyChanged("FlipEnabled");
      if (this.m_tool != null && this.m_mlAvailable)
        CApTPClassificationManager.ClassifyObjectAsync(new ObjectClassificationRequest()
        {
          Object = (ITxObject) this.DummyTool,
          PreviewImages = objSnapshotsFilePath
        }, (Action<object, string, string>) ((obj, resultPreview, result) =>
        {
          if (obj != this.DummyTool)
            return;
          this.ToolClassifyResultPreview = resultPreview;
          this.ToolClassifyResult = result;
          this.OnPropertyChanged("ApplyEnabled");
          this.OnPropertyChanged("FlipEnabled");
        }));
      if (!flag)
        return;
      TxApplication.RefreshDisplay();
    }
  }

  public ITxLocatableObject Fastener
  {
    get => this.m_fastener;
    set
    {
      if (value == this.m_fastener)
        return;
      bool flag = false;
      if (this.m_fastener != null)
      {
        TxDisplayableObjectEx.StopEmphasizeObject(this.m_fastener as ITxDisplayableObject, this.m_fastenerEmphasizeColor, (TxColorEmphasizePriority) 2);
        this.m_fastener.AbsoluteLocationChanged -= new TxLocatableObject_AbsoluteLocationChangedEventHandler(this.CApTPJumpToolViewModel_AbsoluteLocationChanged);
        flag = true;
      }
      this.m_fastener = value;
      if (this.m_fastener != null)
      {
        TxDisplayableObjectEx.EmphasizeObject(this.m_fastener as ITxDisplayableObject, this.m_fastenerEmphasizeColor, (TxColorEmphasizePriority) 2);
        this.m_fastener.AbsoluteLocationChanged += new TxLocatableObject_AbsoluteLocationChangedEventHandler(this.CApTPJumpToolViewModel_AbsoluteLocationChanged);
        flag = true;
      }
      this.FastenerClassifyResultPreview = this.FastenerClassifyResult = string.Empty;
      this.OnPropertyChanged(nameof (Fastener));
      this.Jumped = false;
      this.CompatibilityResult = string.Empty;
      List<string> objSnapshotsFilePath = new List<string>();
      try
      {
        TxApplication.ActiveUndoManager.StartTransaction();
        this.RemoveFromPreview((ITxObject) this.DummyFastener);
        this.DeleteObject((ITxObject) this.DummyFastener);
        this.DummyFastener = (ITxLocatableObject) null;
        this.FastenerAssemblyComponent = (ITxACFastener) null;
        if (this.m_fastener != null)
        {
          this.DummyFastener = this.CreateDummyObject(this.m_fastener);
          if (this.DummyFastener != null)
          {
            this.CreatePreview(this.DummyFastener, objSnapshotsFilePath);
            this.m_dummyFastenerOriginalLocation = this.DummyFastener.AbsoluteLocation;
            this.PreviewFastenerState = this.m_previewGraphics.KeepState();
          }
        }
      }
      finally
      {
        TxUndoTransactionManagerEx.CancelTransaction();
      }
      this.OnPropertyChanged("ApplyEnabled");
      this.OnPropertyChanged("FlipEnabled");
      if (this.m_fastener != null && this.m_mlAvailable)
        CApTPClassificationManager.ClassifyObjectAsync(new ObjectClassificationRequest()
        {
          Object = (ITxObject) this.DummyFastener,
          PreviewImages = objSnapshotsFilePath
        }, (Action<object, string, string>) ((obj, resultPreview, result) =>
        {
          if (obj != this.DummyFastener)
            return;
          this.FastenerClassifyResultPreview = resultPreview;
          this.FastenerClassifyResult = result;
          this.OnPropertyChanged("ApplyEnabled");
          this.OnPropertyChanged("FlipEnabled");
        }));
      if (!flag)
        return;
      TxApplication.RefreshDisplay();
    }
  }

  public bool CompatibilityCheckType
  {
    get => this.m_compatibilityCheckType;
    set
    {
      this.m_compatibilityCheckType = value;
      this.OnPropertyChanged(nameof (CompatibilityCheckType));
    }
  }

  public bool CompatibilityCheckSize
  {
    get => this.m_compatibilityCheckSize;
    set
    {
      this.m_compatibilityCheckSize = value;
      this.OnPropertyChanged(nameof (CompatibilityCheckSize));
      this.OnPropertyChanged("SizeMatchTolerancesEnabled");
    }
  }

  public bool ApplyEnabled
  {
    get
    {
      if (this.Fastener == null || this.Tool == null || this.Jumped)
        return false;
      if (!this.m_mlAvailable)
        return true;
      return this.FastenerClassifyResult != string.Empty && this.ToolClassifyResult != string.Empty;
    }
  }

  public bool ResetEnabled => this.Jumped;

  public bool FlipEnabled
  {
    get
    {
      if (!this.Jumped || this.FastenerAssemblyComponent == null || this.ToolAssemblyComponent == null)
        return false;
      return ((ITxACComponent) this.FastenerAssemblyComponent).EndEffectors.Count > 1 || ((ITxACComponent) this.ToolAssemblyComponent).EndEffectors.Count > 1;
    }
  }

  public int SizeMatchTolerance
  {
    get => this.m_sizeMatchTolerance;
    set
    {
      if (this.m_sizeMatchTolerance == value)
        return;
      this.m_sizeMatchTolerance = value;
      this.OnPropertyChanged(nameof (SizeMatchTolerance));
    }
  }

  public bool SizeMatchTolerancesEnabled => this.CompatibilityCheckSize;

  private bool Jumped
  {
    get => this.m_jumped;
    set
    {
      if (this.m_jumped == value)
        return;
      this.m_jumped = value;
      this.OnPropertyChanged("ApplyEnabled");
      this.OnPropertyChanged("ResetEnabled");
      this.OnPropertyChanged("FlipEnabled");
    }
  }

  public bool ShowClassifyResult { get; set; }

  public bool ClassifyPreviewVisibility
  {
    get => this._classifyPreviewVisibility;
    set
    {
      this._classifyPreviewVisibility = value;
      this.OnPropertyChanged(nameof (ClassifyPreviewVisibility));
    }
  }

  private void UpdateClassificationPreview(List<ITxLocatableObject> previewObjects)
  {
    this.ClassifyPreviewVisibility = false;
    if (!this.ShowClassifyResult || previewObjects == null || previewObjects.Count != 1)
      return;
    this.ClassifyPreviewVisibility = true;
    this.OnPropertyChanged("ClassifyResult");
  }

  public string ClassifyResult
  {
    get
    {
      if (this.PreviewObjects != null && this.PreviewObjects.Count == 1)
      {
        if (this.PreviewObjects[0] == this.DummyTool)
          return this.ToolClassifyResultPreview;
        if (this.PreviewObjects[0] == this.DummyFastener)
          return this.FastenerClassifyResultPreview;
      }
      return string.Empty;
    }
  }

  private string ToolClassifyResultPreview
  {
    get => this._toolClassifyResult;
    set
    {
      this._toolClassifyResult = value;
      this.OnPropertyChanged("ClassifyResult");
    }
  }

  private string ToolClassifyResult { get; set; }

  private string FastenerClassifyResultPreview
  {
    get => this._fastenerClassifyResult;
    set
    {
      this._fastenerClassifyResult = value;
      this.OnPropertyChanged("ClassifyResult");
    }
  }

  private string FastenerClassifyResult { get; set; }

  public string CompatibilityResult
  {
    get => this.m_compatibilityResult;
    private set
    {
      if (!(this.m_compatibilityResult != value))
        return;
      this.m_compatibilityResult = value;
      if (this.m_compatibilityResult == string.Empty)
        this._graphicsDrawer.Clear();
      this.OnPropertyChanged(nameof (CompatibilityResult));
    }
  }

  private string ClassifyEndEffector(ITxACEndEffector endEff)
  {
    foreach (TxContour shapeContour in endEff.ShapeContours)
    {
      if (shapeContour.Points != null && shapeContour.Points.Count > 0)
        return this.ClassifyShapeContour(shapeContour);
    }
    return string.Empty;
  }

  private string ClassifyShapeContour(TxContour contour)
  {
    contour.Center = new TxTransformation(new TxVector(), new TxVector(), (TxTransformation.TxRotationType) 1);
    List<TxVector> txVectorList = CApTPIContourManipulator.MakeCloseContour(contour.Points);
    if (txVectorList.Count > 80 /*0x50*/)
      txVectorList = CApTPIContourManipulator.DecimatePolyline(txVectorList, 80 /*0x50*/, out double _);
    else if (txVectorList.Count < 80 /*0x50*/)
      txVectorList = CApTPIContourManipulator.SaturatePolyline(txVectorList, contour.Length / 80.0, 80 /*0x50*/);
    if (this.ShowClassifyResult)
      this._graphicsDrawer.DrawContour(txVectorList, TxColor.TxColorRed, contour.Center.Translation, (TxVector) null, (TxVector) null, 0.1);
    string str = CApTPIContourManipulator.ConvertContourPointsToString(CApTPIContourManipulator.ScaleContour(txVectorList), 80 /*0x50*/);
    if (!this.m_mlAvailable)
      return string.Empty;
    return CApTPClassificationManager.ClassifyContour(new ContourClassificationRequest()
    {
      ContourPoints = new List<string>() { str }
    });
  }

  public void CheckCPUSupportRequiredInstructions()
  {
    this.m_mlAvailable = true;
    if (CApTPClassificationManager.AVXSupported())
      return;
    this.m_mlAvailable = false;
    int num = (int) TxDoNotShowAgainMessageBox.Show(StringTable.CPU_NOT_SUPPORT_AVX, StringTable.CMD_NAME, "SMART_TOOL_POSITION_CPU_NOT_SUPPORT_AVX", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, DialogResult.OK);
  }

  private ITxACTool ToolAssemblyComponent
  {
    get => this.m_toolAssemblyComponent;
    set
    {
      if (this.m_toolAssemblyComponent == value)
        return;
      if (this.m_toolAssemblyComponent != null)
        ((IDisposable) this.m_toolAssemblyComponent).Dispose();
      this.m_toolAssemblyComponent = value;
      this.OnPropertyChanged("FlipEnabled");
    }
  }

  private ITxACFastener FastenerAssemblyComponent
  {
    get => this.m_fastenerAssemblyComponent;
    set
    {
      if (this.m_fastenerAssemblyComponent == value)
        return;
      if (this.m_fastenerAssemblyComponent != null)
        ((IDisposable) this.m_fastenerAssemblyComponent).Dispose();
      this.m_fastenerAssemblyComponent = value;
      this.OnPropertyChanged("FlipEnabled");
    }
  }

  public void Apply()
  {
    this.ApplyFocused();
    ITxComponent tool = this.Tool as ITxComponent;
    ITxComponent fastener = this.Fastener as ITxComponent;
    bool flag1 = true;
    if (tool == null || fastener == null)
      return;
    string message = (string) null;
    string exceptionType = (string) null;
    Mouse.OverrideCursor = System.Windows.Input.Cursors.Wait;
    bool flag2 = false;
    if ((this.IsExactGeometry(tool) || this.IsExactGeometry(fastener)) && (this.CompatibilityCheckSize || this.CompatibilityCheckType) && TxDoNotShowAgainMessageBox.Show(StringTable.MSG_EXACT_GEOMETRY_OBJECT, StringTable.CMD_NAME, "MSG_EXACT_GEOMETRY_OBJECT", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation, DialogResult.Yes) == DialogResult.No)
    {
      Mouse.OverrideCursor = (System.Windows.Input.Cursor) null;
    }
    else
    {
      if (!this.IsDisplayed(tool) || !this.IsDisplayed(fastener))
      {
        TxApplication.ActiveUndoManager.StartTransaction();
        this.VerifyDisplayState(tool);
        this.VerifyDisplayState(fastener);
        TxApplication.ActiveUndoManager.EndTransaction();
      }
      try
      {
        this.Jumped = false;
        this.CompatibilityResult = string.Empty;
        TxACGeometryExplorer geometryExplorer = new TxACGeometryExplorer();
        ITxACComponent itxAcComponent1 = (ITxACComponent) null;
        ITxACComponent itxAcComponent2 = (ITxACComponent) null;
        TxApplication.ActiveUndoManager.StartTransaction();
        flag2 = true;
        if (this.FastenerAssemblyComponent == null && geometryExplorer.Explore(fastener, this.FastenerClassifyResult, false, 1.0, ref itxAcComponent2))
        {
          this.FastenerAssemblyComponent = itxAcComponent2 as ITxACFastener;
          if (itxAcComponent2 != null && itxAcComponent2.DummyComponent != null)
            TxGraphicViewerEx.The.RemoveObject((ITxObject) itxAcComponent2.DummyComponent);
          this.ToolAssemblyComponent = (ITxACTool) null;
        }
        double num = this.FastenerAssemblyComponent == null || ((ITxACComponent) this.FastenerAssemblyComponent).ActiveEndEffector == null ? 1.0 : ((ITxACComponent) this.FastenerAssemblyComponent).ActiveEndEffector.ShapeContourDepth;
        if (this.ToolAssemblyComponent == null && geometryExplorer.Explore(tool, this.ToolClassifyResult, true, num, ref itxAcComponent1))
        {
          this.ToolAssemblyComponent = itxAcComponent1 as ITxACTool;
          if (itxAcComponent1 != null && itxAcComponent1.DummyComponent != null)
            TxGraphicViewerEx.The.RemoveObject((ITxObject) itxAcComponent1.DummyComponent);
        }
        flag2 = false;
        TxUndoTransactionManagerEx.CancelTransaction();
        if (this.ToolAssemblyComponent == null || this.FastenerAssemblyComponent == null || !this.AreTypeCompatible(this.ToolAssemblyComponent, this.FastenerAssemblyComponent, out message) || !this.AreSizeCompatible(this.ToolAssemblyComponent, this.FastenerAssemblyComponent, out message))
          return;
        TxApplication.ActiveUndoManager.StartTransaction();
        this.FastenerAssemblyComponent.Assemble(this.ToolAssemblyComponent, flag1);
        TxApplication.ActiveUndoManager.EndTransaction();
        TxApplication.ActiveUndoManager.StartTransaction();
        this.JumpDummyToolOnDummyFastener();
        TxUndoTransactionManagerEx.CancelTransaction();
        this.Jumped = true;
      }
      catch (TxAssemblyComponentsCannotMoveObjectException ex)
      {
        message = StringTable.TOOL_CANNOT_MOVE;
        exceptionType = ((Exception) ex).GetType().Name;
      }
      catch (TxAssemblyComponentsCannotReadGeometryException ex)
      {
        message = StringTable.CMD_TOOL_POSITION_FAILED;
        exceptionType = ((Exception) ex).GetType().Name;
      }
      catch (TxToolPositioningToolDoesNotMatchFastenerException ex)
      {
        message = StringTable.TOOL_AND_FASTENER_TYPES_ARE_INCOMPATIBLE;
        exceptionType = ((Exception) ex).GetType().Name;
      }
      catch (TxUnknownErrorException ex)
      {
        message = StringTable.CMD_TOOL_POSITION_FAILED;
        exceptionType = ((Exception) ex).GetType().Name;
      }
      catch (TxException ex)
      {
        message = ((Exception) ex).Message;
        exceptionType = ((Exception) ex).GetType().Name;
      }
      finally
      {
        Mouse.OverrideCursor = (System.Windows.Input.Cursor) null;
        if (flag2 || !this.Jumped)
          TxUndoTransactionManagerEx.CancelTransaction();
        TxApplication.RefreshDisplay();
        this.LogSmartToolResultToSoftwareAnalytics(exceptionType);
        if (message != null)
        {
          int num = (int) TxMessageBox.Show(message, StringTable.CMD_NAME, MessageBoxButtons.OK, MessageBoxIcon.Hand);
        }
      }
    }
  }

  public void Reset()
  {
    if (!this.Jumped || this.Tool == null)
      return;
    this.Tool.AbsoluteLocation = this.m_toolOriginalLocation;
    this.Jumped = false;
    this.ClassifyPreviewVisibility = false;
    this.CompatibilityResult = string.Empty;
    TxApplication.ActiveUndoManager.StartTransaction();
    this.DummyTool.AbsoluteLocation = this.m_dummyToolOriginalLocation;
    this.DummyFastener.AbsoluteLocation = this.m_dummyFastenerOriginalLocation;
    TxUndoTransactionManagerEx.CancelTransaction();
    TxApplication.RefreshDisplay();
  }

  public void Clear()
  {
    TxAssemblyComponents.DeleteCacheInfo();
    this.Tool = (ITxLocatableObject) null;
    this.Fastener = (ITxLocatableObject) null;
    CApTPClassificationManager.UnloadModel();
  }

  public void FlipTool()
  {
    if (!this.FlipEnabled)
      return;
    if (((ITxACComponent) this.ToolAssemblyComponent).EndEffectors.Count > 1)
      ((ITxACComponent) this.ToolAssemblyComponent).ChangeActiveEndEffector();
    else if (((ITxACComponent) this.FastenerAssemblyComponent).EndEffectors.Count > 1)
      ((ITxACComponent) this.FastenerAssemblyComponent).ChangeActiveEndEffector();
    this.Apply();
  }

  public bool FastenerFocused()
  {
    if (this.Jumped)
      return false;
    if (this.PreviewObjects != null && this.PreviewObjects.Count == 1)
    {
      if (this.PreviewObjects[0] == this.DummyFastener)
        return false;
      if (this.PreviewObjects[0] == this.DummyTool)
        this.PreviewToolState = this.m_previewGraphics.KeepState();
    }
    if (this.DummyFastener == null)
      return false;
    this.PreviewObjects = new List<ITxLocatableObject>()
    {
      this.DummyFastener
    };
    this.m_previewGraphics.RestoreState(this.PreviewFastenerState);
    return true;
  }

  public bool ToolFocused()
  {
    if (this.Jumped)
      return false;
    if (this.PreviewObjects != null && this.PreviewObjects.Count == 1)
    {
      if (this.PreviewObjects[0] == this.DummyTool)
        return false;
      if (this.PreviewObjects[0] == this.DummyFastener)
        this.PreviewFastenerState = this.m_previewGraphics.KeepState();
    }
    if (this.DummyTool == null)
      return false;
    this.PreviewObjects = new List<ITxLocatableObject>()
    {
      this.DummyTool
    };
    this.m_previewGraphics.RestoreState(this.PreviewToolState);
    return true;
  }

  public bool ApplyFocused()
  {
    if (this.Jumped || this.PreviewObjects == null || this.PreviewObjects.Count != 1)
      return false;
    if (this.PreviewObjects[0] == this.DummyTool)
      this.PreviewToolState = this.m_previewGraphics.KeepState();
    else if (this.PreviewObjects[0] == this.DummyFastener)
      this.PreviewFastenerState = this.m_previewGraphics.KeepState();
    return true;
  }

  private void JumpDummyToolOnDummyFastener()
  {
    try
    {
      this.DummyTool.AbsoluteLocation = TxTransformation.op_Multiply(this.DummyFastener.AbsoluteLocation, TxTransformation.op_Multiply(this.Fastener.AbsoluteLocation.Inverse, this.Tool.AbsoluteLocation));
      this.PreviewObjects = new List<ITxLocatableObject>()
      {
        this.DummyTool,
        this.DummyFastener
      };
      this.m_previewGraphics.AdjustCameraPosition(this.PreviewFastenerState != null ? this.PreviewFastenerState.CameraPosition : new TxVector(), true);
    }
    catch
    {
    }
  }

  private void VerifyDisplayState(ITxComponent obj)
  {
    if (!(obj is ITxDisplayableObject displayableObject))
      return;
    displayableObject.Display();
  }

  private bool IsDisplayed(ITxComponent obj)
  {
    if (!(obj is ITxDisplayableObject displayableObject))
      return false;
    return displayableObject.Visibility == null || displayableObject.Visibility == 1;
  }

  private void DeleteObject(ITxObject obj)
  {
    if (obj == null || !obj.IsValid() || !obj.CanBeDeleted)
      return;
    obj.Delete();
  }

  private void CApTPJumpToolViewModel_AbsoluteLocationChanged(
    object sender,
    TxLocatableObject_AbsoluteLocationChangedEventArgs args)
  {
    this.Jumped = false;
  }

  public bool AreTypeCompatible(ITxACTool tool, ITxACFastener fastener, out string message)
  {
    message = (string) null;
    if (this.CompatibilityCheckType)
    {
      string toolContourType = this.ClassifyEndEffector(((ITxACComponent) tool).ActiveEndEffector);
      string fastenerContourType = this.ClassifyEndEffector(((ITxACComponent) fastener).ActiveEndEffector);
      if (this.ShowClassifyResult)
      {
        double num = ((ITxACComponent) fastener).ActiveEndEffector != null ? ((ITxACComponent) fastener).ActiveEndEffector.ShapeContourDepth : 0.0;
        this.CompatibilityResult = $"{toolContourType}, {fastenerContourType} Depth: {num.ToString("0.00")}";
      }
      if (!this.m_compatibilityChecker.MatchType(((ITxACComponent) tool).ActiveEndEffector.Type, ((ITxACComponent) fastener).ActiveEndEffector.Type, toolContourType, fastenerContourType))
      {
        message = StringTable.TOOL_AND_FASTENER_TYPES_ARE_INCOMPATIBLE;
        return false;
      }
    }
    return true;
  }

  public bool AreSizeCompatible(ITxACTool tool, ITxACFastener fastener, out string message)
  {
    message = (string) null;
    if (this.CompatibilityCheckSize)
    {
      ITxACEndEffector activeEndEffector1 = ((ITxACComponent) tool).ActiveEndEffector;
      ITxACEndEffector activeEndEffector2 = ((ITxACComponent) fastener).ActiveEndEffector;
      if (activeEndEffector1 != null && activeEndEffector2 != null && activeEndEffector1.ShapeContours.Count > 0 && activeEndEffector2.ShapeContours.Count > 0)
      {
        TxContour shapeContour1 = activeEndEffector1.ShapeContours[0];
        TxContour shapeContour2 = activeEndEffector2.ShapeContours[0];
        if (shapeContour1.Points.Count > 0 && shapeContour2.Points.Count > 0)
        {
          List<TxVector> points1 = shapeContour1.Points;
          double closestDist1;
          CApTPIContourManipulator.FindClosestContourPointFromContourCenter(shapeContour1.Center.Translation, points1, out closestDist1);
          double farthestDist1;
          CApTPIContourManipulator.FindFarthestContourPointFromContourCenter(shapeContour1.Center.Translation, points1, out farthestDist1);
          List<TxVector> points2 = shapeContour2.Points;
          double closestDist2;
          CApTPIContourManipulator.FindClosestContourPointFromContourCenter(shapeContour2.Center.Translation, points2, out closestDist2);
          double farthestDist2;
          CApTPIContourManipulator.FindFarthestContourPointFromContourCenter(shapeContour2.Center.Translation, points2, out farthestDist2);
          if (farthestDist1 > 0.0 && farthestDist2 > 0.0 && closestDist1 > 0.0 && closestDist2 > 0.0)
          {
            if (this.ShowClassifyResult)
            {
              this.CompatibilityResult += this.CompatibilityResult != string.Empty ? ";" : "";
              this.CompatibilityResult = $"{this.CompatibilityResult}BD: {Math.Abs(farthestDist1 - farthestDist2).ToString("0.00")} - {this.m_compatibilityChecker.LogTolerance(farthestDist1, farthestDist2, this.SizeMatchTolerance)}";
              this.CompatibilityResult = $"{this.CompatibilityResult}; SD: {Math.Abs(closestDist1 - closestDist2).ToString("0.00")} - {this.m_compatibilityChecker.LogTolerance(closestDist1, closestDist2, this.SizeMatchTolerance)}";
            }
            if (!this.m_compatibilityChecker.MatchSize(farthestDist1, farthestDist2, this.SizeMatchTolerance) || !this.m_compatibilityChecker.MatchSize(closestDist1, closestDist2, this.SizeMatchTolerance))
            {
              message = StringTable.TOOL_AND_FASTENER_SIZES_ARE_INCOMPATIBLE;
              return false;
            }
          }
        }
      }
    }
    return true;
  }

  private void LogSmartToolResultToSoftwareAnalytics(string exceptionType)
  {
    if (!TxSoftwareAnalyticsServices.isLoggerEnabled())
      return;
    ITxComponent tool = this.Tool as ITxComponent;
    ITxComponent fastener = this.Fastener as ITxComponent;
    if (tool == null || fastener == null)
      return;
    TxSoftwareAnalyticsServicesMsg message = this.CreateMessage();
    message.addProperty("Tool", this.ToolClassifyResultPreview);
    message.addProperty("Fastener", this.FastenerClassifyResultPreview);
    message.addProperty("Tool Geometry", this.IsExactGeometry(tool) ? "exact" : "approx");
    message.addProperty("Fastener Geometry", this.IsExactGeometry(fastener) ? "exact" : "approx");
    message.addProperty("Result", string.IsNullOrEmpty(exceptionType) ? "success" : "failure");
    message.addProperty("Exception", string.IsNullOrEmpty(exceptionType) ? string.Empty : exceptionType);
    TxSoftwareAnalyticsServices.log(message);
  }

  private bool IsExactGeometry(ITxComponent comp)
  {
    bool flag = false;
    try
    {
      if (comp != null)
        flag = TxComponentEx.DoesHaveExactGeometryOnly(comp);
    }
    catch
    {
    }
    return flag;
  }

  private TxSoftwareAnalyticsServicesMsg CreateMessage()
  {
    TxSoftwareAnalyticsServicesMsg message = new TxSoftwareAnalyticsServicesMsg();
    message.Type = "Smart Tool Position";
    message.addProperty("Dialog Session", this.m_dialogSession);
    return message;
  }

  private ITxLocatableObject DummyTool { get; set; }

  private ITxLocatableObject DummyFastener { get; set; }

  private GraphicControlPreviewState PreviewToolState { get; set; }

  private GraphicControlPreviewState PreviewFastenerState { get; set; }

  private List<ITxLocatableObject> PreviewObjects
  {
    get => this.m_previewObjects;
    set
    {
      if (this.m_previewObjects != null)
        this.m_previewObjects.ForEach((Action<ITxLocatableObject>) (o => this.m_previewGraphics.RemoveObject((ITxObject) o)));
      this.m_previewObjects = value;
      if (this.m_previewObjects != null)
        this.m_previewObjects.ForEach((Action<ITxLocatableObject>) (o => this.m_previewGraphics.AddObject((ITxObject) o)));
      this.UpdateClassificationPreview(this.m_previewObjects);
    }
  }

  private CApTPIDataGenerator DataGenerator { get; }

  private void BlankFrames(ITxObjectCollection obj)
  {
    if (obj == null)
      return;
    foreach (ITxObject allDescendant in (Collection<ITxObject>) obj.GetAllDescendants((ITxTypeFilter) new TxTypeFilter(typeof (TxFrame))))
    {
      if (allDescendant != null && allDescendant.IsValid() && allDescendant is ITxDisplayableObject)
        (allDescendant as ITxDisplayableObject).Blank();
    }
  }

  private void RemoveFromPreview(ITxObject obj)
  {
    if (this.PreviewObjects == null || this.PreviewObjects.Count <= 0)
      return;
    List<ITxLocatableObject> itxLocatableObjectList = new List<ITxLocatableObject>((IEnumerable<ITxLocatableObject>) this.PreviewObjects);
    itxLocatableObjectList.Remove(obj as ITxLocatableObject);
    if (this.PreviewObjects.Count == 2 && obj == this.DummyFastener && this.PreviewToolState != null)
      this.PreviewToolState.ResetView();
    this.PreviewObjects = itxLocatableObjectList.Count != 0 ? itxLocatableObjectList : (List<ITxLocatableObject>) null;
    this.m_previewGraphics.Refresh();
  }

  private ITxLocatableObject CreateDummyObject(ITxLocatableObject obj)
  {
    TxComponent dummyObject = (TxComponent) null;
    try
    {
      using (TxLocalComponentCreationData componentCreationData = new TxLocalComponentCreationData("SmartToolDummyObject", obj.AbsoluteLocation))
      {
        componentCreationData.SetAsDisplay();
        dummyObject = TxApplication.ActiveDocument.PhysicalRoot.CreateLocalComponent(componentCreationData);
      }
      if (TxComponent.op_Inequality(dummyObject, (ITxObject) null))
      {
        TxComponent txComponent = dummyObject;
        TxObjectList txObjectList = new TxObjectList();
        ((Collection<ITxObject>) txObjectList).Add((ITxObject) obj);
        TxObjectCollectionEx.Paste((ITxObjectCollection) txComponent, txObjectList, true, true);
        this.BlankFrames((ITxObjectCollection) dummyObject);
        TxGraphicViewerEx.The.RemoveObject((ITxObject) dummyObject);
        dummyObject.Display();
      }
    }
    catch
    {
    }
    return (ITxLocatableObject) dummyObject;
  }

  private void CreatePreview(ITxLocatableObject dummyObj, List<string> objSnapshotsFilePath)
  {
    this.DataGenerator.LastSavedImagesPath.Clear();
    this.PreviewObjects = (List<ITxLocatableObject>) null;
    if (dummyObj == null)
      return;
    this.DataGenerator.Object = dummyObj;
    this.PreviewObjects = new List<ITxLocatableObject>()
    {
      dummyObj
    };
    this.DataGenerator.Generate(10);
    TxTransformation absoluteLocation = dummyObj.AbsoluteLocation;
    this.DataGenerator.Object = (ITxLocatableObject) null;
    dummyObj.AbsoluteLocation = absoluteLocation;
    objSnapshotsFilePath.AddRange((IEnumerable<string>) this.DataGenerator.LastSavedImagesPath);
  }

  private void DataGenerator_GeneratingDataExample(ITxObject obj)
  {
    using (Bitmap snapshot = this.m_previewGraphics.GetSnapshot(new Size(CUiTPIGraphicControlHelper.Width, CUiTPIGraphicControlHelper.Height)))
    {
      if (snapshot == null)
        return;
      this.DataGenerator.SaveImage((Image) snapshot, obj.Name, "");
    }
  }

  private void DataGenerator_GenerationStarted(ITxObject obj)
  {
    this.m_previewGraphics.AdjustCameraPosition(this.DataGenerator.ObjectApproachDirection);
    ITxDisplayableObject displayableObject = obj as ITxDisplayableObject;
    try
    {
      this._restoreColor = displayableObject.Color;
    }
    catch
    {
      this._restoreColor = (TxColor) null;
    }
    displayableObject.Color = CUiTPIGraphicControlHelper.PreviewColor();
  }

  private void DataGenerator_GenerationFinished(ITxObject obj)
  {
    ITxDisplayableObject displayableObject = obj as ITxDisplayableObject;
    if (TxColor.op_Inequality(this._restoreColor, (TxColor) null))
    {
      displayableObject.Color = this._restoreColor;
      this._restoreColor = (TxColor) null;
    }
    else
      displayableObject.RestoreColor();
    this.m_previewGraphics.Refresh();
  }
}
